package cmd

import (
	"os"
	"text/template"

	"lanmon/internal/config"

	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

// when updating this template, don't forget to update config.md!
const configTemplate = `
[general]
# Log level
# debug=5, info=4, warning=3, error=2, fatal=1, panic=0
log_level={{ .General.LogLevel }}
# 0 -- client, 1 -- server
launch_server={{ .General.LaunchServer }}
mdns_address="{{ .General.MdnsAddress }}"
port_backend={{ .General.PortBackend }}

[mqtt]
# MQTT topic templates for the different MQTT topics.
#
# C -> S
event_topic="{{ .MQTT.EventTopic }}"

# Command topic template.
# S -> C
#
# Use:
#   * "{{ "{{ .ClientID }}" }}" as an substitution for the LoRa gateway ID
command_topic_template="{{ .MQTT.CommandTopicTemplate }}"
broadcast_topic="{{ .MQTT.BroadcastTopic }}"

# MQTT server (e.g. scheme://host:port where scheme is tcp, ssl or ws)
server="{{ .MQTT.Server }}"

# Connect with the given username (optional)
username="{{ .MQTT.Username }}"

# Connect with the given password (optional)
password="{{ .MQTT.Password }}"

# Maximum interval that will be waited between reconnection attempts when connection is lost.
# Valid units are 'ms', 's', 'm', 'h'. Note that these values can be combined, e.g. '24h30m15s'.
max_reconnect_interval="{{ .MQTT.MaxReconnectInterval }}"

# Quality of service level
#
# 0: at most once
# 1: at least once
# 2: exactly once
#
# Note: an increase of this value will decrease the performance.
# For more information: https://www.hivemq.com/blog/mqtt-essentials-part-6-mqtt-quality-of-service-levels
qos={{ .MQTT.QOS }}

# Clean session
#
# Set the "clean session" flag in the connect message when this client
# connects to an MQTT broker. By setting this flag you are indicating
# that no messages saved by the broker for this client should be delivered.
clean_session={{ .MQTT.CleanSession }}

# Client ID
#
# Set the client id to be used by this client when connecting to the MQTT
# broker. A client id must be no longer than 23 characters. When left blank,
# a random id will be generated. This requires clean_session=true.
client_id="{{ .MQTT.ClientID }}"
`

var configCmd = &cobra.Command{
	Use:   "configfile",
	Short: "Print the configuration file",
	RunE: func(cmd *cobra.Command, args []string) error {
		t := template.Must(template.New("config").Parse(configTemplate))
		err := t.Execute(os.Stdout, config.C)
		if err != nil {
			return errors.Wrap(err, "execute config template error")
		}
		return nil
	},
}
